package com.aliyun.heiyu.powermaster.server.rotary.dao.impl;

import com.aliyun.heiyu.powermaster.proto.CabinetsAndServer;
import com.aliyun.heiyu.powermaster.proto.CabinetsAndServerReply;
import com.aliyun.heiyu.powermaster.server.rotary.contants.ServerSqlContant;
import com.aliyun.heiyu.powermaster.server.rotary.dao.ServerDAO;
import com.aliyun.heiyu.powermaster.server.rotary.object.dto.CabinetDTO;
import com.aliyun.heiyu.powermaster.server.rotary.object.dto.ServerDTO;
import com.aliyun.heiyu.powermaster.server.rotary.object.dto.ServerIdDTO;
import com.aliyun.heiyu.powermaster.server.rotary.object.entity.DeviceCommonEntity;
import com.aliyun.heiyu.powermaster.server.rotary.object.entity.ServerCollectInfoEntity;
import com.aliyun.heiyu.powermaster.server.rotary.utils.JdbcUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Description 服务器实现类
 * @Author shun.zhang
 * @Date 2019/12/31 9:56
 **/
public class ServerDAOImpl implements ServerDAO {
    private static Logger logger = LoggerFactory.getLogger(ServerDAOImpl.class);

    String queryServer = "SELECT server_sn,server_power,cpu_usage,collect_time FROM state_grid_collect_info WHERE server_sn = ? ORDER BY collect_time DESC LIMIT 1";

    @Override
    public int saveServerData(ServerCollectInfoEntity serverCollectInfoEntity) {
        Object[] data = new Object[4];
        data[0] = serverCollectInfoEntity.getGmt_create();
        data[1] = serverCollectInfoEntity.getCollect_time();
        data[2] = serverCollectInfoEntity.getServer_sn();
        data[3] = serverCollectInfoEntity.getInlet_temp();
        return JdbcUtil.insert(ServerSqlContant.SAVE_SERVERDATA, data);
    }

    @Override
    public List<DeviceCommonEntity> getServerList() {
        return JdbcUtil.queryForList(ServerSqlContant.SELECT_SERVERLIST, null, DeviceCommonEntity.class);
    }


    @Override
    public List<CabinetDTO> getCabinetsAndServerTemp() {
        List<CabinetDTO> cabinetDTOS = new ArrayList<>();
        try {
            //1.查询所有机柜
            List<CabinetDTO> cabinetS = JdbcUtil.queryForList(ServerSqlContant.USER_CABINET, null, CabinetDTO.class);
            if (CollectionUtils.isEmpty(cabinetS)) {
                return null;
            }
            //2.查询该机柜下温度最高的的服务器
            for (CabinetDTO cabinetDTO : cabinetS) {
                cabinetDTO.setServer_sn(cabinetDTO.getDevice_id());//解决别名的问题修复 2020-12-23
                //1>查询该机柜下的所有服务器主键
                Object[] obj = new Object[1];
                obj[0] = cabinetDTO.getDevice_id();
                List<ServerIdDTO> serverIdDTOS = JdbcUtil.queryForList(ServerSqlContant.GET_SERVER_IDS, obj, ServerIdDTO.class);
                if (!CollectionUtils.isEmpty(serverIdDTOS)) {
                    List<CabinetDTO> cabinetDTOList = new ArrayList<>();
                    for (ServerIdDTO cabinet : serverIdDTOS) {
                        Object[] serverId = new Object[1];
                        serverId[0] = cabinet.getDevice_id();
                        CabinetDTO cabi = JdbcUtil.queryForBean(ServerSqlContant.SERVER_TEMP, serverId, CabinetDTO.class);
                        if (null != cabi) {
                            cabi.setLocated_cabinet(cabinetDTO.getDevice_id());//解决20210105 修改
                            cabinetDTOList.add(cabi);
                        }
                    }
                    //2>获取温度最高的服务器
                    // for(cabDTOs){}
                    if (!CollectionUtils.isEmpty(cabinetDTOList)) {
                        CabinetDTO cabin = new CabinetDTO();
                        cabin.setInlet_temp(new BigDecimal(0));
                        for (CabinetDTO cabinetDTO1 : cabinetDTOList) {
                            if (null != cabinetDTO1.getInlet_temp()) {
                                if (cabinetDTO1.getInlet_temp().compareTo(cabin.getInlet_temp()) > 0) {
                                    cabin = cabinetDTO1;
                                }
                            }
                        }
                        cabinetDTOS.add(cabin);
                    }
                }
            }
            return cabinetDTOS;
        } catch (Exception e) {
            logger.info("获取系统中机柜及其温度最高服务器异常", e);
            return null;
        }
    }

    @Override
    public List<CabinetDTO> queryMicrothermCabinetServerTemp(){
        try {
            //查询出推荐机柜温度最低的一个
            List<CabinetDTO> cabinetS = JdbcUtil.queryForList(ServerSqlContant.SERVER_LOWEST_TEMPERATURE, null, CabinetDTO.class);
            //1.查询所有机柜
           if (CollectionUtils.isEmpty(cabinetS)) {
                return null;
            }else{
                for(CabinetDTO cabinetDTO:cabinetS){
                    Object[] obj = new Object[1];
                    obj[0] = cabinetDTO.getServer_sn();
                    CabinetDTO dto= JdbcUtil.queryForBean(ServerSqlContant.SERVER_OWNING_CABINET, obj, CabinetDTO.class);
                    cabinetDTO.setLocated_cabinet(dto.getLocated_cabinet());

                }
                return cabinetS;
            }
        } catch (Exception e) {
            logger.info("获取系统中机柜及其温度最低服务器异常", e);
            return null;
        }
    }


    /**
     * 获取map中第一个数据值
     *
     * @param map 数据源
     * @return
     */
    private static Object getFirstOrNull(TreeMap<BigDecimal, Object> map) {
        Object obj = null;
        for (Map.Entry<BigDecimal, Object> entry : map.entrySet()) {
            obj = entry.getValue();
            if (obj != null) {
                break;
            }
        }
        return obj;
    }



    @Override
    public CabinetsAndServerReply.Data getCabinetTempByDeviceId(String device_id) {
        CabinetsAndServerReply.Data.Builder data = CabinetsAndServerReply.Data.newBuilder();
        try {
            //TODO 后期优化
            //1.先通过机柜获取机柜下的服务器
            Object[] cabinetId = new Object[1];
            cabinetId[0] = device_id;
            List<ServerIdDTO> serverIds = JdbcUtil.queryForList(ServerSqlContant.SERVER_IDS_BY_CABINET, cabinetId, ServerIdDTO.class);
            //2.查询每台服务器最新的功率跟温度
            data.setLocatedCabinet(device_id);
            if (CollectionUtils.isEmpty(serverIds)) {
                return data.build();
            }
            for (ServerIdDTO serverId : serverIds) {
                CabinetsAndServer.Builder serverDT = CabinetsAndServer.newBuilder();
                Object[] server = new Object[1];
                server[0] = serverId.getDevice_id();
                ServerDTO serverDTO = JdbcUtil.queryForBean(ServerSqlContant.SERVER_TEMP_POWER_ID, server, ServerDTO.class);

                if(serverDTO ==null || serverDTO.equals("")){
                    continue;
                }
                try {
                    serverDT.setInletTemp(serverDTO.getInlet_temp());
                } catch (Exception e) {
                    serverDT.setInletTemp(0);
                }
                serverDT.setServerSn(serverDTO.getServer_sn());
                try {
                    serverDT.setServerPower(serverDTO.getServer_power());
                } catch (Exception e) {
                    serverDT.setServerPower(0);
                }

                data.addCabinets(serverDT);
            }
            return data.build();
        } catch (Exception e) {
            logger.error("根据机柜中服务器数据异常", e);
            return data.build();
        }
    }

}
